﻿using CustomForm.Common.Extensions;
using CustomForm.Entities;
using CustomForm.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace CustomForm.Controllers
{
    public class LoginController : Controller
    {
        private readonly ILogger<LoginController> _logger;
        private readonly IFreeSql _sql;

        public LoginController(ILogger<LoginController> logger, IFreeSql sql)
        {
            _logger = logger;
            _sql = sql;
        }

        [HttpGet]
        public IActionResult Index()
        {
            return View(new LoginRequest());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Index(LoginRequest request)
        {
            if (ModelState.IsValid)
            {
                var loginUser = _sql.Select<User>().Where(u => u.username == request.adminuser && u.password == request.adminpass.MD5(true)).ToOne();
                if (loginUser != null)
                {
                    HttpContext.Session.Set(nameof(AdminSession), new AdminSession()
                    {
                        adminid = loginUser.id,
                        adminuser = loginUser.username,
                        adminqx = loginUser.quanxian,
                        danwei = loginUser.danwei,
                    });
                    return Redirect("~/");
                }

                ModelState.AddModelError(string.Empty, "用户名或密码错误");
            }

            return View(request);
        }
    }
}
